import re
import redis


def get_dim_field_info(dim_name, win_conn, path):
    '''
    获取维度具体字段信息
    :param dim_name: 维度名称
    :param win_conn: cube所在远程主机连接
    :param path: cube所在远程主机文件路径
    :return:
    '''
    redis_conn = redis.Redis(host='127.0.0.1', port=6379, db=12)
    redis_key = "{}-{}-{}-dim-field-info".format(win_conn.host, path, dim_name)

    if not redis_conn.get(redis_key):
        file_names = win_conn.get_files('*.dim.xml', path)
        content = ''
        for file_name in file_names:
            if dim_name in file_name:
                content = win_conn.get_file_connect(file_name, path).replace("\r\n", "")
        redis_conn.set(redis_key, content, ex=60 * 60 * 24)  # ex参数设置60s过期
    else:
        content = redis_conn.get(redis_key).decode('utf-8').replace("\r\n", "")
    redis_conn.close()
    # 匹配条件
    field_info_pat = re.compile("<Attribute>(.*?)</Attribute>")
    content_list = field_info_pat.findall(content)
    name_pat = re.compile("<Name>(.*?)</Name>")
    field_pat = re.compile("<ColumnID>(.*?)</ColumnID>")
    result_list = []
    for item in content_list:
        item_dict = {"name": name_pat.findall(item)[0], "field": field_pat.findall(item)[0]}
        result_list.append(item_dict)

    return result_list


if __name__ == '__main__':
    from app_cube.utils.connect.my_win import MyWin

    win_conn = MyWin('127.0.0.1', 'Administrator', 'zjs')
    path = r'C:\Program Files\Microsoft SQL Server\MSAS11.MSSQLSERVER\OLAP\Data\YWC_SSAS.0.db'
    content = get_dim_field_info(dim_name="日期", win_conn=win_conn, path=path)
    print(content)
